<?php
namespace Wap\Controller;
use Think\Controller;
class ApiController extends Controller{
	
	public function index(){
		exit('无权限访问!');
	}
	public function exchangeCheck(){
		$wechat_id = I('wechat_id');
		$status = $this->isAuthExchange($wechat_id);
		echo json_encode($status);
	}
	public function exchangePrize(){
		$res = array('success'=>'0','code'=>'unknow error');
		$wechat_id = I('wechat_id');
		$name = I('name');
		$phonenum = I('phonenum');
		$area = I('area');
		$address = I('address');
		$status = $this->isAuthExchange($wechat_id);
		if($status['success']==1){
			$data['integral'] = $this->userinfo['integral'] - $this->prizeinfo['cost'];
			//扣除积分
			$updateStatus = M('juejin_users')->where(['open_id'=>$wechat_id])->save($data);
			if($updateStatus){
				//ADD address
				$addressData['userid'] = $this->userinfo['id'];
				$addressData['prizeid'] = $this->prizeinfo['id'];
				$addressData['updatetime'] = time();
				$addressData['name'] = $name;
				$addressData['phonenum'] = $phonenum;
				$addressData['area'] = $area;
				$addressData['address'] = $address;
				$newAddressID = M('juejin_address')->add($addressData);
				//ADD log
				$logData['userid'] = $this->userinfo['id'];
				$logData['createtime'] = time();
				$logData['num'] = '-'.$this->prizeinfo['cost'];
				$logData['addressid'] = $newAddressID;
				$logData['note'] = '兑换奖品：(ID-'.$this->prizeinfo['id'].')'.$this->prizeinfo['name'];
				M('juejin_integral_log')->add($logData);
				//扣除库存
				M('juejin_prize')->where(['id'=>$this->prizeinfo['id']])->setInc('odd');
				$res = array('success'=>'1','code'=>'success');	
			}else{
				$res = array('success'=>'0','code'=>'积分扣除失败，请稍后再试');
			}
		}else{
			$res = $status;
		}
		echo json_encode($res);
	}
	//Exchange Prize Auth
	protected function isAuthExchange($wechat_id){
		$res = array('success'=>'0','code'=>'unknow error');
		//是否有openid
		if($wechat_id){
			$this->userinfo = M('juejin_users')->where(['open_id'=>$wechat_id])->find();
			//是否有用户信息
			if($this->userinfo){
				$this->prizeinfo = M('juejin_prize')->where('status=1 AND count-odd>0')->find();
				//获取奖品info
				if($this->prizeinfo){
					if($this->userinfo['integral']>=$this->prizeinfo['cost']){
						$res = array('success'=>'1','code'=>'success');	
						/*$data['integral'] = $userinfo['integral'] - $prizeinfo['cost'];
						//扣除积分
						$updateStatus = M('juejin_users')->where('status=1 AND odd>0')->save($data);
						if($updateStatus){
							$res = array('success'=>'1','code'=>'success');	
						}else{
							$res = array('success'=>'0','code'=>'积分扣除失败，请稍后再试');
						}*/
					}else{
						$res = array('success'=>'0','code'=>'剩余积分不足');
					}
				}else{
					$res = array('success'=>'0','code'=>'无可兑换奖品');
				}
			}else{
				$res = array('success'=>'0','code'=>'非法访问2');
			}
		}else{
			$res = array('success'=>'0','code'=>'非法访问1');
		}
		return $res;
	}

}